import React, { Component,Fragment } from 'react'
// antd
import {Form,Input,Button,Table,message,Modal,Select,Checkbox,Pagination,Row,Col} from "antd"
//api
import {GetList,GetUser,Delete,addOne,editOne,totalusers} from "../../api/user"
import { PlusOutlined,EditOutlined,DeleteOutlined,SearchOutlined,  } from '@ant-design/icons';
// import Demo from "../../components/header/tabs"
const { Option } = Select;
export default class User extends Component {
    state = {
        keyword:"",
        //请求参数
        limit: 10,
        offset: 0,
        id:"",
        selectedRowKeys: [],
        visible:false,
        visible_edit:false,
        visible_add:false,
        is_active:true,
        is_active_edit:true,
        total:0,
        loading: false, // 是否正在获取数据中
        // is_active_edit:true,
        columns:[
            {title: "姓名",dataIndex:"username",key:"username"},
            {title: "角色",dataIndex:"roles",key:"roles"},
            {title: "是否有效",dataIndex:"is_active",key:"is_active"},
            {
                title: "操作",
                dataIndex:"operation",
                key:"operation", 
                width:215,
                render: (text, rowData) => {
                    return (
                        <div className="inline-button">
                            <Button type="primary" onClick={()=> this.onHanderEdit(rowData.username)} icon={<EditOutlined />}>
                                编辑
                            </Button>
                            <Button onClick={() => this.onHanderDelete(rowData.username)} icon={<DeleteOutlined />}>删除</Button>
                        </div>
                    )
                }
            },
        ],
        data:[]
    }
    /** 生命周期挂载完成 */
    componentDidMount(){
        this.loadData();
        this.getUserNumber();
    }
    /** 删除 */
    onHanderDelete = (username) => {
        this.setState({
            visible:true,
            id:username,
        })
        
    }
    /** 编辑 */
    onHanderEdit = (username) => {
        this.setState({
            visible_edit:true,
            id:username,
        })
    }
    /** 加载页面 */
    loadData = () => {
        const requestData = {
            limit: this.state.limit,
            offset: this.state.offset
        }
        GetList(requestData).then(response =>{
            // console.log(response.data.length)
            this.setState({loading: true})
            const responseData = response.data
            this.setState({loading:false})
            let maps = new Map([[true,'有效'],[false,'无效']]);
            responseData.map( obj =>{
                obj.is_active = maps.get(obj.is_active)
            })
            if(responseData){
                this.setState({
                    data:responseData,
                })
            }
        }).catch(error =>{
            console.log(error);
        })
    }
    /** 获得用户总数 */
    getUserNumber = ()=>{
        totalusers().then(response =>{
            // console.log(response.data)
            if(response.data){
                this.setState({
                    total:response.data
                })
            }
        }).catch(error =>{
            console.log(error)
        })
    }
    /** 删除弹窗 */
    hideModal = ()=>{
        const {id : username} = this.state
        Delete(username).then(response => {
            const mess = "删除成功"
            // console.log(response.data)
            message.info(mess)
            this.setState({
                visible:false,
                id:"",
            })
            //请求数据
            this.loadData()
            this.getUserNumber()
        })
    }
    /** 搜索 */
    onFinish = (value)=>{
        const {username:user} = value
        // console.log(user)
        if(user){
            GetUser(user).then(response =>{
                const dataList = []
                const responseData = response.data
                dataList.push(responseData)
                // console.log(dataList)
                // console.log(responseData)
                let maps = new Map([[true,'有效'],[false,'无效']]);
                dataList.map( obj => {
                    obj.is_active = maps.get(obj.is_active)
                })
                if(dataList){
                    this.setState({
                        data:dataList
                    })
                }
            }).catch( error =>{
                console.log(error)
                this.setState({
                    data:[]
                })
            })
        }else{
            this.loadData();
        }      
    }
    /** 显示添加人员弹窗 */
    onHanderAdd = () => {
        this.setState({
            visible_add:true,
        })
    }
    /** 复选框 */
    onCheckeBox = (selectedRowKeys) => {
        this.setState({selectedRowKeys})
    }

    /**
     * 添加用户
     */
    addOne =(values)=>{
        const {username,password, roles:role} = values
        const {is_active} = this.state
        const resData = {username,password,is_active,role}
        addOne(resData).then( response => {
            const mess = "添加成功"
            // console.log(response.data)
            message.info(mess)
            this.loadData()
            this.getUserNumber()
            console.log(response)
        }).catch(error => {
            console.log(error)
        })
    }
    /**
     * 编辑用户 
     */
    editOne = (values) =>{
        const {password, roles:role} = values
        const {is_active_edit,id:user,loading,} = this.state
        const resData = {password,is_active:is_active_edit,role}
        
        
        editOne(user,resData).then(response => {
            this.loadData()
            alert("数据已修改")
            console.log(response)
        }).catch(error => {
            console.log(error)
        })
        console.log(user)
        console.log(resData);
    }
    /**
     * 改变添加时is_active的状态
     */
    onChangeIs_active = (e)=>{
        this.setState({
            is_active:e.target.checked
        }) 
        // console.log("是否选中：",this.state.is_active)
    }
    /**
     * 改变编辑时is_active的状态
     */
    onChangeIs_active_edit = (e) => {
        this.setState({
            is_active_edit:e.target.checked
        })
    }

    /**
     * 当前页码
     */
    onChangeCurrentPage = (value) => {
        // console.log(value)
        const {limit} =this.state
        this.setState({
            offset:limit*(value-1),
        },()=>{
            // console.log(this.state.offset)
            this.loadData();
        })           
    }
    /**
     * 下拉页面
     */
    onChangeSizePage = (value,page) => {
        this.setState({
           offset: 0,
           limit: page,
        }, () => {
            this.loadData()
        })
    }
    render() {
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 8 },
          };
        const formTailLayout = {
            labelCol: {
              span: 4,
            },
            wrapperCol: {
              span: 8,
              offset: 0,
            },
        };
        
        const {columns,data,id,loading} = this.state
        const rowSelection = {
            onChange: this.onCheckeBox
        }
        return (
            <div>
                {/* <Demo /> */}
                <div className="uuuu">                   
                    <div className="tttt">
                    {/* <span>kk</span> */}
                        <Form layout="inline" onFinish={this.onFinish}>
                            <Form.Item label="用户名" name="username">
                                <Input placeholder="请输入用户名" />
                            </Form.Item>    
                            <Form.Item>
                                <Button type="primary" htmlType="submit" icon={<SearchOutlined/>}>
                                    搜索
                                </Button>
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" onClick={this.onHanderAdd} icon={<PlusOutlined />}>
                                    添加
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>                
                </div>
                
                
                <div className="table-row">
                    <Table 
                    className="table-wrap"
                    //  pagination={{pageSize:10}}
                    
                    pagination={false}
                    rowSelection={rowSelection} 
                    rowKey="username" 
                    columns={columns} 
                    dataSource={data} 
                    bordered>
                    loading = {loading}
                     </Table>
                     <hr color={'#f5f5f5'}/>
                    <Row style={{marginTop:8}}>
                        <Col span={8}></Col>
                        <Col span={16}>
                            <Pagination 
                                onChange={this.onChangeCurrentPage}
                                onShowSizeChange={this.onChangeSizePage}
                                pageSize={this.state.limit}
                                className="pull-right"
                                defaultCurrent={1}
                                showSizeChanger
                                showQuickJumper
                                total={this.state.total} 
                                showTotal={total => `总计 ${total} 条` }
                            />
                        </Col>
                    </Row>               
                </div>
                {/* 删除弹窗 */}
                <Modal
                title="提示"
                visible={this.state.visible}
                onOk={this.hideModal}
                onCancel={() => {this.setState({visible:false})}}
                okText="确认"
                cancelText="取消"
                >
                    <p className="text-center">确认删除此信息？<strong className="color-red">删除后将无法恢复。</strong></p>
                </Modal>

                {/* 编辑弹窗 */}
                <Modal title={`编辑${id}用户信息`}
                visible={this.state.visible_edit}   //设置默认隐藏
                onCancel={() => {this.setState({visible_edit:false})}}
                footer={false}   //对话框的底部
                >
                <Form
                    onFinish={this.editOne}
                >
                    <Form.Item {...formItemLayout} label="密码" name="password" rules={[
                        { required: true, message: '密码不能为空!' },
                        ({getFieldValue}) => ({
                            validator(role,value){
                                let passwords_value = getFieldValue("passwords");
                                if(passwords_value && value !== passwords_value){
                                    return Promise.reject("两次密码不一致")
                                }
                                return Promise.resolve();
                            }
                        })
                        ]}>
                            <Input  type="password" placeholder="Password"/>
                    </Form.Item>
                        
                    <Form.Item {...formItemLayout} label="确认密码" name="passwords" rules={[
                        { required: true, message: '密码不能为空!' },
                        ({getFieldValue}) => ({
                            validator(role,value){
                                if(value !== getFieldValue("password")){
                                    return Promise.reject("两次密码不一致")
                                }
                                return Promise.resolve();
                            }
                        })
                        ]}>
                        <Input  type="password" placeholder="Password"/>
                    </Form.Item>

                    <Form.Item {...formTailLayout} name="roles" label="角色" style={{ width: 480 }} rules={[{ required: true }]}>
                        <Select
                        placeholder="选择"
                        onChange={this.onGenderChange}
                        allowClear
                        >
                        <Option value="appuser">appuser</Option>
                        <Option value="admin">admin</Option>
                        <Option value="admin,superadmin">admin,superadmin</Option>
                        </Select>
                    </Form.Item>
                    
                    <Form.Item {...formItemLayout}  label="is_active"  rules={[{message: '选择是否有效' }]}>
                        <Checkbox  defaultChecked="true" onChange={this.onChangeIs_active_edit}>有效</Checkbox>
                    </Form.Item>
                    <Form.Item  >
                        <Button type="primary" htmlType="submit"> 提交 </Button>
                    </Form.Item>
                </Form>
                </Modal>

                {/* 添加弹窗 */}
                <Modal
                title="添加用户"
                visible={this.state.visible_add}
                onCancel={() => {this.setState({visible_add:false})}}
                footer={false}
                >
                <Form
                    onFinish={this.addOne}
                >
                    <Form.Item {...formItemLayout} label="用户名" name="username" rules={[{ required: true, message: 'Please input your Username!' }]}> 
                        <Input placeholder="Username"/> 
                    </Form.Item>

                    <Form.Item {...formItemLayout} label="密码" name="password" rules={[
                        { required: true, message: '密码不能为空!' },
                        ({getFieldValue}) => ({
                            validator(role,value){
                                let passwords_value = getFieldValue("passwords");
                                if(passwords_value && value !== passwords_value){
                                    return Promise.reject("两次密码不一致")
                                }
                                return Promise.resolve();
                            }
                        })
                        ]}>
                            <Input  type="password" placeholder="Password"/>
                    </Form.Item>
                        
                    <Form.Item {...formItemLayout} label="确认密码" name="passwords" rules={[
                        { required: true, message: '密码不能为空!' },
                        ({getFieldValue}) => ({
                            validator(role,value){
                                if(value !== getFieldValue("password")){
                                    return Promise.reject("两次密码不一致")
                                }
                                return Promise.resolve();
                            }
                        })
                        ]}>
                        <Input  type="password" placeholder="Password"/>
                    </Form.Item>

                    <Form.Item {...formTailLayout} name="roles" label="角色" style={{ width: 480 }} rules={[{ required: true }]}>
                        <Select
                        placeholder="选择"
                        onChange={this.onGenderChange}
                        allowClear
                        >
                        <Option value="appuser">appuser</Option>
                        <Option value="admin">admin</Option>
                        <Option value="admin,superadmin">admin,superadmin</Option>
                        </Select>
                    </Form.Item>
                    
                    <Form.Item {...formItemLayout}  label="is_active"  rules={[{message: '选择是否有效' }]}>
                        <Checkbox  defaultChecked="true" onChange={this.onChangeIs_active}>有效</Checkbox>
                    </Form.Item>
                    <Form.Item >
                        <Button type="primary" htmlType="submit" icon={<PlusOutlined />}> 添加 </Button>
                    </Form.Item>

                </Form>
                </Modal>
            </div>
        )
    }
}
